package com.frog.service.friend.service.relation;


import com.alibaba.fastjson.JSON;
import com.frog.common.util.ConstantUtil;
import com.frog.service.friend.common.CommonStringUtil;
import com.frog.service.friend.mapper.FriendAddMessageDOMapper;
import com.frog.service.friend.model.RelationModel;
import com.frog.service.friend.model.domain.FriendAddMessageDO;
import com.frog.service.friend.model.domain.FriendFollowingRelationshipDO;
import com.frog.service.friend.service.cache.FriendFollowService;
import com.frog.service.friend.service.friendList.MaintainRelationService;
import com.frog.service.friend.utils.FriendRelationshipUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


/**
 * 好友关注关系实例
 */
@Slf4j
@Service("friendRelationInstance")
public class FriendRelation implements Relation {

    @Autowired
    private FriendFollowService friendFollowService;
    @Autowired
    private FriendAddMessageDOMapper friendAddMessageDOMapper;
    @Autowired
    private MaintainRelationService maintainRelationService;


    /**
     * 添加好友关系
     *
     * @param userId       主动发起人
     * @param friendUserId 被动添加人
     * @return 添加完成后状态
     */
    @Override
    public boolean establish(Integer userId, Integer friendUserId) {
        Long id = FriendRelationshipUtil.processRelationId(userId, friendUserId);
        if (id == null || id == 0) return false;
        FriendFollowingRelationshipDO f = friendFollowService.select(String.valueOf(id));
        return f == null ? initAddFollow(id, userId, friendUserId) : renewAddFollow(id, userId, friendUserId, f);
    }

    /**
     * 解除好友关系
     *
     * @param userId       主动发起人
     * @param friendUserId 被动解除关系人
     * @return 解除关系后状态
     */
    @Override
    public boolean termination(Integer userId, Integer friendUserId) {
        Long id = FriendRelationshipUtil.processRelationId(userId, friendUserId);
        if (id == null || id == 0) return false;
        FriendFollowingRelationshipDO f = friendFollowService.select(String.valueOf(id));
        return renewCancelFollow(id, userId, friendUserId, f);
    }


    // ------------------------------------------------------------------------------------------------------------------------------
    // 关注好友方法

    /**
     * 关注好友,初始化好友关系
     */
    private boolean initAddFollow(Long id, Integer userId, Integer friendUserId) {
        long time = System.currentTimeMillis();

        // 初始化关系写入存储层和缓存层
        FriendFollowingRelationshipDO f = FriendFollowingRelationshipDO.builder().id(id)
                .fromUserId(userId).toUserId(friendUserId)
                .followStatus(CommonStringUtil.FriendBothStatus.sendConcerned)
                .bestStatus(CommonStringUtil.FriendBothStatus.notConcerned)
                .blockStatus(CommonStringUtil.FriendBothStatus.notConcerned)
                .cancelStatus(CommonStringUtil.FriendBothStatus.notConcerned)
                .createTime(time)
                .updateTime(time)
                .followTime(time)
                .build();
        if (!friendFollowService.save(id, f)) return false;

        // 保存friendList
        RelationModel r = new RelationModel(id, userId, userId, friendUserId, CommonStringUtil.FriendBothStatus.notConcerned, true);
        maintainRelationService.addFollow(r);

        // 好友关系写入成功后,存储关系添加记录表
        FriendAddMessageDO m = FriendAddMessageDO.builder()
                .id(id)
                .fromUserId(userId).toUserId(friendUserId)
                .addStatus(CommonStringUtil.FriendBothStatus.sendConcerned)
                .deleteStatus(ConstantUtil.common.STATUS_0)
                .messageReadStatus(ConstantUtil.common.STATUS_0)
                .createTime(time)
                .updateTime(time)
                .build();
        Integer status = 0;
        try {
            status = friendAddMessageDOMapper.insertMessage(m);
        } catch (Exception exception) {
            log.error("initAddFollow friendAddMessage exception: ", exception);
        }
        return status != 0;
    }


    /**
     * 关注好友,更新好友关系
     */
    private boolean renewAddFollow(Long id, Integer userId, Integer friendUserId, FriendFollowingRelationshipDO f) {
        if (f == null) return false;
        if (userId == null || friendUserId == null) return false;
        long time = System.currentTimeMillis();
        // 验证添加好友关系
        RelationModel r = new RelationModel(id, userId, f.getFromUserId(), f.getToUserId(), f.getFollowStatus(), true);
        if (!r.isSuccessStatus()) return false;
        // 更新好友关系
        Map<String, Object> fieldMap = new HashMap<>();
        fieldMap.put("follow_status", r.getStatusLater());
        fieldMap.put("update_time", time);
        fieldMap.put("follow_time", time);
        // 更新好友关系失败返回
        if (!friendFollowService.modify(id, fieldMap)) return false;
        // 保存friendList
        maintainRelationService.addFollow(r);
        // 更新好友操作消息表
        updateFriendAddMessage(id, userId, friendUserId);
        return true;
    }


    // ------------------------------------------------------------------------------------------------------------------------------
    // 取消关注好友方法

    /**
     * 取消好友,更新好友关系
     */
    private boolean renewCancelFollow(Long id, Integer userId, Integer friendUserId, FriendFollowingRelationshipDO f) {
        if (f == null) return false;
        if (userId == null || friendUserId == null) return false;

        // 将要修改成的目标好友关系状态值
        Integer fromUserId = f.getFromUserId();
        Integer toUserId = f.getToUserId();
        RelationModel r = new RelationModel(id, userId, fromUserId, toUserId, f.getFollowStatus(), false);
        if (!r.isSuccessStatus()) return false;

        // cancelStatus字段值
        String cancelStatus = f.getFromUserId().equals(userId) ? CommonStringUtil.FriendBothStatus.unilateralAttention : CommonStringUtil.FriendBothStatus.mutualConcern;

        // 更新好友关系
        long time = System.currentTimeMillis();
        Map<String, Object> fieldMap = new HashMap<>();
        fieldMap.put("follow_status", r.getStatusLater());
        fieldMap.put("update_time", time);
        fieldMap.put("follow_time", time);
        fieldMap.put("cancel_status", cancelStatus);
        if (!friendFollowService.modify(id, fieldMap)) return false;

        // 更新好友关系成功后
        // 更新friendList缓存列表
        maintainRelationService.delFollow(r);

        // 更新消息列表
        FriendAddMessageDO friendAddMessageDO = null;
        try {
            friendAddMessageDO = friendAddMessageDOMapper.selectFriendAddMessageById(id);
            if (friendAddMessageDO != null) {
                friendAddMessageDO.setUpdateTime(time);
                if (friendAddMessageDO.getFromUserId().equals(userId)) {
                    if (friendAddMessageDO.getAddStatus().equals(CommonStringUtil.FriendBothStatus.sendConcerned)) {
                        friendAddMessageDO.setAddStatus(CommonStringUtil.FriendBothStatus.notConcerned);
                        friendAddMessageDOMapper.updateFriendAddMessageById(friendAddMessageDO);
                    }
                }
            }
        } catch (Exception e) {
            log.error("renewCancelFollow friendAddMessageDOMapper id:{} FriendAddMessageDO==={},", id, JSON.toJSONString(friendAddMessageDO), e);
            return false;
        }
        return true;
    }


    protected void updateFriendAddMessage(Long id, Integer userId, Integer friendUserId) {
        try {
            FriendAddMessageDO fm = friendAddMessageDOMapper.selectFriendAddMessageById(id);
            if (fm == null) return;

            FriendAddMessageDO updateFm = new FriendAddMessageDO();
            updateFm.setId(id);
            updateFm.setUpdateTime(System.currentTimeMillis());


            //当前用户发起者，状态是已取消，删除，更新数据
            if (fm.getFromUserId().equals(userId)) {
                if (fm.getAddStatus().equals(CommonStringUtil.FriendBothStatus.notConcerned) ||
                        fm.getDeleteStatus().equals(ConstantUtil.common.STATUS_1)) {
                    updateFm.setAddStatus(CommonStringUtil.FriendBothStatus.sendConcerned);
                    updateFm.setDeleteStatus(ConstantUtil.common.STATUS_0);
                    friendAddMessageDOMapper.updateFriendAddMessageById(updateFm);
                }
            } else {
                //当前用户为被邀请者，状态是邀请者邀请,取消，删除，更新数据
                if (fm.getAddStatus().equals(CommonStringUtil.FriendBothStatus.notConcerned)
                        || fm.getAddStatus().equals(CommonStringUtil.FriendBothStatus.sendConcerned)
                        || fm.getDeleteStatus().equals(ConstantUtil.common.STATUS_1)) {
                    if (fm.getAddStatus().equals(CommonStringUtil.FriendBothStatus.notConcerned)
                            && !fm.getDeleteStatus().equals(ConstantUtil.common.STATUS_1)) {
                        updateFm.setFromUserId(userId);
                        updateFm.setToUserId(friendUserId);
                        updateFm.setAddStatus(CommonStringUtil.FriendBothStatus.sendConcerned);
                    } else {
                        updateFm.setAddStatus(CommonStringUtil.FriendBothStatus.mutualConcern);
                    }
                    friendAddMessageDOMapper.updateFriendAddMessageById(updateFm);
                }
            }
        } catch (Exception e) {
            log.error("renewAddFollow update FriendAddMessageDO fail", e);
        }
    }

}